<?php

namespace app\model;

use think\Model;

class Base extends Model
{

    /**
     * 创建随机编号
     *
     * @param string $field
     * @param int $length
     * @param int $capital
     * @return string
     */
    public function rankNum(string $field = 'num', int $length = 6, int $capital = 0): string
    {
        $arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        $num = '';
        for ($i = 1; $i <= $length; $i++) {
            $num .= $arr[rand(0, count($arr) - 1)];
        }
        if ($capital == 1) {
            $num = strtoupper($num); //转换成大写
        }

        $res = $this->where($field, $num)->findOrEmpty();
        if (!$res->isEmpty()) {
            return $this->rankNum($field, $length, $capital);
        } else {
            return $num;
        }
    }
}